package org.streets.eis;

import java.util.Locale;

import org.apache.wicket.Request;
import org.apache.wicket.Session;
import org.streets.commons.util.DigestUtils;
import org.streets.database.PV;
import org.streets.database.SQLConnection;
import org.streets.wicket.HiveWebSession;

import org.streets.eis.entity.User;


public class EisWebSession extends HiveWebSession {

	private static final long serialVersionUID = -2094987911098411061L;
	
	protected User user = null;
	protected boolean signedIn = false;
	
	
	public static EisWebSession get() {		
		return (EisWebSession)Session.get();
	}
	
	public EisWebSession(Request request) {
		super(request);
		setLocale(Locale.SIMPLIFIED_CHINESE);
	}
	

	public User getUser() {
		return user;
	}
	
	public boolean authenticate(final String username, final String password) {
		SQLConnection conn = EisApplication.get().getRegistry().service(SQLConnection.class);
		user = conn.unique("select * from eis_user where user_id = ? and pass = ?", User.class, PV.of(username, DigestUtils.md5Hex(password)));
		return user != null;
	}
	
	/**
	 * @return True if the user is signed in to this session
	 */
	public final boolean isSignedIn() 	{
		return signedIn;
	}

	/**
	 * Signs user in by authenticating them with a username and password
	 * 
	 * @param username
	 *            The username
	 * @param password
	 *            The password
	 * @return True if the user was signed in successfully
	 */
	public final boolean signIn(final String username, final String password) {
		return signedIn = authenticate(username, password);
	}
	/**
	 * Unsigned current login user
	 */
	public final void signOut() {
		signedIn = false;
		user = null;
	}	
}

